<?php
namespace app\home\controller;
use app\common\model\User as UserModel;
use app\home\controller\Verify;
use app\home\model\Token;
use think\facade\Cache;
use yichenthink\utils\MakeId;
use yichenthink\utils\ReturnMsg;

// use think\facade\Session;

class Login extends Base {

	public $tokenExpires = 3600; //token有效期

	public function login($username = '', $password = '', $captcha = '验证码') {

		$code = 400;
		$data = [];
		$mess = '';

		(new Verify)->verifyCaptcha($captcha);

		$user = UserModel::where('username', $username)->find();
		if (Null !== $user) {
			if ($user['state'] != -1) {
				if ($user['password'] === $password) {
					$tokenExpires = time() + $this->tokenExpires;
					$code = 200;

					$cache = [
						'uid' => $user['id'],
						'token' => MakeId::Token(),
						'expires' => $tokenExpires,
					];
					$data['token'] = $cache;
					$data['userInfo'] = $user->hidden(['password', 'delete_time'])->toArray();
					// 缓存登陆状态
					Cache::set('login' . $user['id'], $cache, $this->tokenExpires);
				} else {
					$mess = '密码不正确';
				}
			} else {
				$mess = '用户被屏蔽';
			}

		} else {
			$mess = '用户不存在';
		}
		ReturnMsg::returnMsg($code, $mess, $data);
	}
	public function register($username = '', $password = '', $captcha = '验证码') {
		$code = 400;
		$mess = '';

		(new Verify)->verifyCaptcha($captcha);

		$user = new UserModel;
		$checkData = UserModel::where('username', $username)->find();

		if (Null == $checkData) {
			$code = 200;
			$user->username = $username;
			$user->password = $password;
			$user->id = MakeId::User();
			$user->createtime = time();
			$user->updatetime = time();
			$user->nickname = $username;
			$user->save();
		} else {
			$mess = '用户名已存在';
		}

		ReturnMsg::returnMsg($code, $mess, $user);
	}
	// 重置登陆信息
	public function resetLogin() {
		$user = UserModel::where('id', $this->userInfo['uid'])->find();
		$mess = '';
		$data = [];
		if (Null !== $user) {
			$tokenExpires = time() + $this->tokenExpires;
			$code = 200;
			$data['userInfo'] = $user;
			$cache = [
				'uid' => $user['id'],
				'token' => MakeId::Token(),
				'expires' => $tokenExpires,
			];
			$data['token'] = $cache;
			// 缓存登陆状态
			Cache::set('login' . $user['id'], $cache, $this->tokenExpires);

		} else {
			$mess = '用户不存在';
		}
		ReturnMsg::returnMsg($code, $mess, $data);
	}
}
